﻿using System;
using System.IO;
using ZilLion.Core.Log;
using ZilLion.Core.TaskManager.Client.Core;

namespace ZilLion.Core.TaskManager.Client.SystemMonitor
{
    /// <summary>
    ///     任务性能监控者
    ///     用于检测当前任务运行的性能情况，通知到数据库
    /// </summary>
    public class TaskPerformanceMonitor : BaseMonitor
    {
        public override int Interval
        {
            get { return 5000; }
        }

        private static long DirSize(DirectoryInfo directoryInfod)
        {
            long size = 0;
            // 所有文件大小.
            var fis = directoryInfod.GetFiles();
            foreach (var fi in fis)
                size += fi.Length;
            // 遍历出当前目录的所有文件夹.
            var dis = directoryInfod.GetDirectories();
            foreach (var di in dis)
                size += DirSize(di); //这就用到递归了，调用父方法,注意，这里并不是直接返回值，而是调用父返回来的
            return size;
        }

        protected override void Run()
        {
            //性能 监控

            foreach (var taskruntimeinfo in TaskRuntimePool.GetInstance().AppDomainPool)
                try
                {
                    if (taskruntimeinfo.Key.IsNullOrEmpty() || (taskruntimeinfo.Value == null))
                        continue;
                    var domain = taskruntimeinfo.Value.Domain;

                    var fileinstallpath = taskruntimeinfo.Value.Domain.BaseDirectory;
                  
                    double dirsizeMb = -1;
                    if (Directory.Exists(fileinstallpath))
                    {
                        var dirsize = DirSize(new DirectoryInfo(fileinstallpath));
                        dirsizeMb = (double) dirsize/1024/1024;
                    }
                    try
                    {
                        if (domain != null)
                            try
                            {
                                var cpu = domain.MonitoringTotalProcessorTime.TotalSeconds;
                                var memory = domain.MonitoringSurvivedMemorySize;
                                ZilLionLogManager.GetLogger()
                                    .Info(
                                        $"cpu = {cpu},memory ={(double) memory/1024/1024},installdirsize = {dirsizeMb},dllname = {taskruntimeinfo.Key}");
                            }
                            catch (AppDomainUnloadedException)
                            {
                            }
                    }
                    catch (Exception ex)
                    {
                        ZilLionLogManager.GetLogger().Error(ex: ex, tags: "任务性能监控时出错");
                    }
                }
                catch (Exception exp)
                {
                    ZilLionLogManager.GetLogger().Error(ex: exp, tags: "任务性能监控者出错");
                }
        }
    }
}